package com.buba.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.buba.mapper.SpareLedgerMapper;
import com.buba.mapper.SpareTypesMapper;
import com.buba.mapper.WareDetailsMapper;
import entity.sparemanage.Outwarehousing;
import com.buba.mapper.OutwarehousingMapper;
import com.buba.service.OutwarehousingService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import entity.sparemanage.SpareLedger;
import entity.sparemanage.WareDetails;
import entity.sparemanage.Warehousing;
import entity.sparemanage.dto.*;
import entity.sparemanage.vo.PeopleVo;
import entity.sparemanage.vo.selAllOutWareHouseVo;
import entity.system.CodeRules;
import feign.systemFeign;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import utils.PageResult;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 出库记录表 服务实现类
 * </p>
 *
 * @author beisheng
 * @since 2023-05-18
 */
@Service
public class OutwarehousingServiceImpl extends ServiceImpl<OutwarehousingMapper, Outwarehousing> implements OutwarehousingService {

    @Autowired
    private OutwarehousingMapper outwarehousingMapper;
    @Autowired
    private systemFeign systemFeign;
    @Autowired
    private WareDetailsMapper wareDetailsMapper;
    @Autowired
    private SpareLedgerMapper spareLedgerMapper;
    @Autowired
    private SpareTypesMapper spareTypesMapper;
    /* *
     * @Author: beisheng
     * @Descriprion: 新增出库记录及出库备件明细
     * @Date: 2023/5/31 14:02
     * @Return: common.R
     * @Param: [insertOutWareDto]
     */

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void insertOutWareDto(insertOutWareDto insertOutWareDto) {
        Outwarehousing outwarehousing = new Outwarehousing();
        BeanUtils.copyProperties(insertOutWareDto,outwarehousing);
        //1.新增入库记录基本信息
        outwarehousing.setApplicant(insertOutWareDto.getApplicant());
        outwarehousing.setApplicantDepart(insertOutWareDto.getApplicantDepart());
        //1.1 查询规则生成入库单号
        CodeRules bj = systemFeign.selAllRules("CK");
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(bj.getDateTime());
        String format = simpleDateFormat.format(new Date());
        List<Outwarehousing> warehousingList = outwarehousingMapper.selectList(new QueryWrapper<Outwarehousing>().eq("delete_flag", 0));
        String code = bj.getPrefix()+format+"0"+(warehousingList.size()+1);
        outwarehousing.setWareCode(code);
        outwarehousing.setDeleteFlag(0);
        outwarehousing.setCreateTime(new Date());
        outwarehousing.setUpdateTime(new Date());
        try {
            outwarehousingMapper.insert(outwarehousing);
        }catch (Exception e){
            throw new RuntimeException("新增出库记录失败",e);
        }
        List<spareLedgerDtos> spareList = insertOutWareDto.getSpareList();
        for (spareLedgerDtos spareLedgerDtos : spareList) {
            //2.新增入库明细
            WareDetails wareDetails = new WareDetails();
            wareDetails.setSpId(spareLedgerDtos.getSpId());
            wareDetails.setLnventoryLimit(spareLedgerDtos.getUpperInventory().toString());
            wareDetails.setLoverLimit(spareLedgerDtos.getLowerInventory().toString());
            wareDetails.setNowLimit(String.valueOf(spareLedgerDtos.getTotalInventory()-Integer.valueOf(spareLedgerDtos.getReceiptQuantity())));
            wareDetails.setWareNumber(spareLedgerDtos.getReceiptQuantity());
            wareDetails.setUseId(outwarehousing.getSpId());
            wareDetails.setCreateTime(new Date());
            wareDetails.setUpdateTime(new Date());
            wareDetails.setFlag(2);
            try {
                wareDetailsMapper.insert(wareDetails);
            }catch (Exception e){
                throw new RuntimeException("新增入库明细失败",e);
            }
            //3.更改备件总库存
            SpareLedger spareLedger = spareLedgerMapper.selectById(spareLedgerDtos.getSpId());
            SpareLedger spareLedger1 = new SpareLedger();
            spareLedger1.setTotalInventory(spareLedger.getTotalInventory()-Integer.valueOf(spareLedgerDtos.getReceiptQuantity()));
            spareLedger1.setSpId(spareLedgerDtos.getSpId());
            try {
                spareLedgerMapper.updateById(spareLedger1);
            }catch (Exception e){
                throw new RuntimeException("修改备件总库存失败",e);
            }
        }
    }

    /* *
     * @Author: beisheng
     * @Descriprion: 全查模糊分页查出库信息
     * @Date: 2023/5/31 15:31
     * @Return: common.R
     * @Param: [warehouseDto]
     */

    @Override
    public PageResult selAllOutWareHouse(warehouseDto warehouseDto) {
        Page<Outwarehousing> outwarehousingPage = new Page<>(warehouseDto.getPage(),warehouseDto.getPageSize());
        OutWareHouseWrapper q = new OutWareHouseWrapper();
        QueryWrapper<Outwarehousing> queryWrapper = q.OutWareHouseWrapper(warehouseDto);
        Page<Outwarehousing> outwarehousingPages = outwarehousingMapper.selectPage(outwarehousingPage, queryWrapper);
        List<Outwarehousing> list = outwarehousingMapper.selectList(new QueryWrapper<Outwarehousing>().eq("delete_flag", 0));
        List<Outwarehousing> records = outwarehousingPages.getRecords();
        List<selAllOutWareHouseVo> selAllOutWareHouseVos = new ArrayList<>();
        for (Outwarehousing record : records) {
            selAllOutWareHouseVo selAllOutWareHouseVo = new selAllOutWareHouseVo();
            PeopleVo peopleVo = systemFeign.selOnePeople(record.getWarePersonid() );
            BeanUtils.copyProperties(record,selAllOutWareHouseVo);
            selAllOutWareHouseVo.setWarePeople(peopleVo);
            List<WareDetails> wareDetails = wareDetailsMapper.selectList(new QueryWrapper<WareDetails>().eq("use_id", record.getSpId()).eq("flag", 2));
            for (int i = 0; i < wareDetails.size(); i++) {
                if (i==0){
                    selAllOutWareHouseVo.setAllNumber(Integer.valueOf(wareDetails.get(i).getWareNumber()));
                }else {
                    selAllOutWareHouseVo.setAllNumber(selAllOutWareHouseVo.getAllNumber()+Integer.valueOf(wareDetails.get(i).getWareNumber()));
                }
            }
            selAllOutWareHouseVos.add(selAllOutWareHouseVo);
        }

        return new PageResult(warehouseDto.getPage(),warehouseDto.getPageSize(),list.size(),selAllOutWareHouseVos);
    }

    @Override
    public insertOutWareDto selOneToWare(Integer id) {
        insertOutWareDto insertOutWareDto = new insertOutWareDto();
        //1.查询基本信息
        Outwarehousing outwarehousing = outwarehousingMapper.selectById(id);
        BeanUtils.copyProperties(outwarehousing,insertOutWareDto);
        //2.查询出库明细
        List<WareDetails> wareDetailsList = wareDetailsMapper.selectList(new QueryWrapper<WareDetails>().eq("use_id", id).eq("flag", 2));
        List<spareLedgerDtos> spareList  = new ArrayList<>();
        for (WareDetails wareDetails : wareDetailsList) {
            spareLedgerDtos spareLedgerDtos = new spareLedgerDtos();
            SpareLedger spareLedger = spareLedgerMapper.selectById(wareDetails.getSpId());
            spareLedger.setSpTypeName(spareTypesMapper.selectById(spareLedger.getSpTypeId()).getSpTypename());
            BeanUtils.copyProperties(spareLedger,spareLedgerDtos);
            spareLedgerDtos.setPosition(wareDetails.getWarehoseCode());
            spareLedgerDtos.setReceiptQuantity(wareDetails.getWareNumber());
            spareList.add(spareLedgerDtos);
        }
        insertOutWareDto.setSpareList(spareList);
        return insertOutWareDto;
    }

    /* *
     * @Author: beisheng
     * @Descriprion: 修改出库记录及出库备件明细
     * @Date: 2023/5/31 19:43
     * @Return: common.R
     * @Param: [warehouseDto]
     */

    @Override
    public void updateOutWare(insertOutWareDto warehouseDto) {
        Outwarehousing outwarehousing = new Outwarehousing();
        BeanUtils.copyProperties(warehouseDto,outwarehousing);
        outwarehousing.setUpdateTime(new Date());
        outwarehousingMapper.updateById(outwarehousing);
        List<WareDetails> wareDetailsList = wareDetailsMapper.selectList(new QueryWrapper<WareDetails>().eq("use_id",warehouseDto.getSpId()));
        for (WareDetails wareDetails : wareDetailsList) {
            SpareLedger spareLedger = spareLedgerMapper.selectById(wareDetails.getSpId());
            spareLedger.setTotalInventory(Integer.valueOf(spareLedger.getTotalInventory())+Integer.valueOf(wareDetails.getWareNumber()));
            spareLedgerMapper.updateById(spareLedger);
        }
        wareDetailsMapper.delete(new QueryWrapper<WareDetails>().eq("use_id",warehouseDto.getSpId()));
        for (spareLedgerDtos spareLedgerDtos : warehouseDto.getSpareList()) {
            //2.新增入库明细
            WareDetails wareDetails = new WareDetails();
            wareDetails.setSpId(spareLedgerDtos.getSpId());
            wareDetails.setLnventoryLimit(spareLedgerDtos.getUpperInventory().toString());
            wareDetails.setLoverLimit(spareLedgerDtos.getLowerInventory().toString());
            wareDetails.setNowLimit(String.valueOf(spareLedgerDtos.getTotalInventory()-Integer.valueOf(spareLedgerDtos.getReceiptQuantity())));
            wareDetails.setWareNumber(spareLedgerDtos.getReceiptQuantity());
            wareDetails.setUseId(outwarehousing.getSpId());
            wareDetails.setCreateTime(new Date());
            wareDetails.setUpdateTime(new Date());
            wareDetails.setFlag(2);
            try {
                wareDetailsMapper.insert(wareDetails);
            }catch (Exception e){
                throw new RuntimeException("新增入库明细失败",e);
            }
            //3.更改备件总库存
            SpareLedger spareLedger = spareLedgerMapper.selectById(spareLedgerDtos.getSpId());
            SpareLedger spareLedger1 = new SpareLedger();
            spareLedger1.setTotalInventory(spareLedger.getTotalInventory()-Integer.valueOf(spareLedgerDtos.getReceiptQuantity()));
            spareLedger1.setSpId(spareLedgerDtos.getSpId());
            try {
                spareLedgerMapper.updateById(spareLedger1);
            }catch (Exception e){
                throw new RuntimeException("修改备件总库存失败",e);
            }
        }
    }
}
